package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import database.DBHandler;


/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }
    
    @Override
    public void init(){
    	try {
			super.init();
		} catch (ServletException e) {
			System.err.println("Error in initializing the login servlet!");
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/login.jsp");	
			dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//TODO change to database handler
		HttpSession session = request.getSession();		
		//DatabaseInterface db = new DBHandler();
		String username = request.getParameter("username");		
		String password = request.getParameter("password");
		/*Member newUser = (Member) session.getAttribute("newUser"); //TODO delete this line when the database would exist
		if (newUser != null){//TODO delete this line when the database would exist
			db.addUser(newUser.getUsername(), newUser.getFirstName(), newUser.getLastName(), //TODO delete this line when the database would exist
					(String) session.getAttribute("password"), newUser.getEMail(),newUser.getGender());*/				
		if (DBHandler.getInstance().login(username, password) == 1){
			session.setAttribute("username", new String(username));
			session.setAttribute("isLoggedIn", new Boolean(true));
			session.setAttribute("isModerator", new Boolean(DBHandler.getInstance().isModerator(username)));
			response.sendRedirect(request.getContextPath() + "/viewForums");
		}
		else {
			session.setAttribute("isLoggedIn", "false");
			session.setAttribute("isLoggedIn", "false");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/Error.jsp");
			request.setAttribute("errorMsg", "Username and password do not match!");
			request.setAttribute("errorLink", "http://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath());
			dispatcher.forward(request, response);
		}
	}
	
	@Override
	public void destroy(){
		super.destroy();
	}

}
